package com.example.closethreadgracefully.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

/**
 * @ClassName MyRunnable
 * @Description
 * @Author huyingliang
 * @Date 2024-04-24 16:03
 */
@Slf4j
public class MyRunnable implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(MyRunnable.class);
    private int threadId;
    private StringRedisTemplate stringRedisTemplate;

    public MyRunnable(int threadId, StringRedisTemplate stringRedisTemplate) {
        this.threadId = threadId;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void run() {
        System.out.println("线程" + threadId + "开始执行");
        for (int i = 1; i < 100000; i++) {
            try {
                //每次调用接口前，都检查一下该线程是否需要停止
                Long stopThread = stringRedisTemplate.opsForSet().remove("stopThread", "58746");

                if (1L == stopThread) {
                    System.out.println("线程" + threadId + "被要求停止");
                    return;
                }

                System.out.println("第" + i + "次请求百度接口");

                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.warn("线程{}被中断", threadId);
                throw new RuntimeException(e);
            }

        }
    }
}
